class parseGoods {

	domain = 'http://121.43.232.161';
	/**
	 * 封装 chrome.storage.local.get 为返回 Promise 的函数
	 * @param {string|Array<string>|Object} keys 要获取的存储键
	 * @returns {Promise<Object>} 返回包含存储数据的 Promise
	 */
	storageGetPromise(keys) {
	    return new Promise((resolve, reject) => {
	        chrome.storage.local.get(keys, (result) => {
	            if (chrome.runtime.lastError) {
	                reject(chrome.runtime.lastError);
	            } else {
	                resolve(result);
	            }
	        });
	    });
	}

	storageSetPromise(key, value) {
		return new Promise((resolve, reject) => {
	    	chrome.storage.local.set({ [key]: value }, () => {
	    		if (chrome.runtime.lastError) {
	    			reject(new Error(`存储失败: ${chrome.runtime.lastError.message}`));
	    			return;
	    		}
	      		resolve({ success: true, key, value });
	    	});
		});
	}

	async getRawDataHtml(url) {
		const data = await this.storageGetPromise(['agent']);
		var response = await fetch(url, {
			method: 'GET',
			credentials: 'include',
			headers: {
				"Content-Type": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
				'User-Agent': data.agent,
			}
		});

		return await response.text();
	}

	getRawData(html) {
		const regex =  /window\.rawData\s*=\s*({.*?})\s*;/s;
		const match = html.match(regex);
		if (!match) {
			return false;
		}
		const rawData = JSON.parse(match[1]);
		return rawData;
	}

	async sendApi(api, reqData, post = 1) {
		const data = await this.storageGetPromise(['cookies', 'apptoken']);
		var post_url = this.domain + api;
		if (post) {
			var response = await fetch(post_url, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
	            	'apptoken': data.apptoken
				},
				body: JSON.stringify(reqData)
			});
		} else {
			//get 把 reqData 变成url传
			var params = this.objectToUrlParams(reqData);
			var response = await fetch(post_url + '?'+ params, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
	            	'apptoken': data.apptoken
				},
			});
		}
		const res = await response.json();
		return res;
	}

	goodsParse(message, sender, sendResponse) {
		var data = this.storageGetPromise(['parse_goods']); // 1为开启 0关闭
	}

	// 搜索网络请求
	async searchNet(data, tabId) {
		var sendData = [];
		for (var i = 0; i < data.length; i++) {
			var goods = data[i].item_data.goods_model;
			var send_item = {
				goodsID : goods.goods_id,
				goodsName: goods.goods_name,
				imgUrl: goods.hd_url,
				linkURL: goods.link_url
			};
			sendData.push(send_item);
		}
		var reqData = {
			data: sendData
		};
		var res = await this.sendApi('/parse/search', reqData);
		if (res.code == 200) {
			chrome.scripting.executeScript({
				target: {tabId: tabId},
				func: (data) => {
					var ul = document.getElementById('result');
					for (var i = 0; i < data.length; i++) {
						var li = document.createElement('li');
						li.textContent = `${data[i].goods_id} == 已记录`;	
						ul.prepend(li);
					}
				},
				args: [res.data]
			});
		}
	}

	async searchResult(message, sender, sendResponse) {
		// 首次加载搜索页面
		var rawData = this.getRawData(message.html);
		console.log(rawData.stores.store.data.ssrListData.list);
		var reqData = {
			data : rawData.stores.store.data.ssrListData.list
		};
		var res = await this.sendApi('/parse/search', reqData);
		if (res.code == 200) {
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: (data) => {
					var ul = document.getElementById('result');
					for (var i = 0; i < data.length; i++) {
						var li = document.createElement('li');
						li.textContent = `${data[i].goods_id} == 已记录`;	
						ul.prepend(li);
					}
				},
				args: [res.data]
			});
		}

		chrome.debugger.attach({ tabId: sender.tab.id }, "1.3", () => {
			chrome.debugger.sendCommand({ tabId: sender.tab.id }, "Network.enable");
		});
	}

}


const parse = new parseGoods();

export default parse;